package org.cent.example.mqtt.consumer.consumer;

import lombok.extern.slf4j.Slf4j;
import org.cent.example.mqtt.consumer.config.prop.MqttProp;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author: cent
 * @email: 292462859@qq.com
 * @date: 2019/2/13.
 * @description:
 */
@Component
public class MqttConsumer implements ApplicationRunner {

    @Autowired
    private MqttClient mqttClient;
    @Autowired
    private MqttProp mqttProp;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        mqttClient.subscribe(mqttProp.getTopic());
        mqttClient.setCallback(new CustomCallback());
    }


    @Slf4j
    static public class CustomCallback implements MqttCallback {

        @Override
        public void connectionLost(Throwable throwable) {
            log.error("失去连接！", throwable);

        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
            log.info("consume message,topic:{},message:{}", s,new String(mqttMessage.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        }
    }

}
